package ink.teamwork.stock.service.impl;

import com.googlecode.genericdao.search.Filter;
import com.googlecode.genericdao.search.Search;
import com.googlecode.genericdao.search.SearchResult;
import ink.teamwork.stock.dao.StockDAO;
import ink.teamwork.stock.entity.Stock;
import ink.teamwork.stock.service.StockService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.List;

@Service
@Transactional
public class StockServiceImpl implements StockService {

    @Autowired
    private StockDAO stockDAO;

    public boolean save(Stock stock) {
        return stockDAO.save(stock);
    }

    public boolean update(Stock stock) {
        try {
            stockDAO.save(stock);
            return true;
        }catch (Exception e){
            return false;
        }
    }

    public SearchResult<Stock> queryPage(int start, int size, String code) {
        Search search = new Search();
        if (StringUtils.isNotBlank(code)){
            search.addFilterOr(Filter.like("name", code), Filter.like("code", code));
        }
        search.setFirstResult(start);
        search.setMaxResults(size);
        search.addSort("ct", true);
        return stockDAO.searchAndCount(search);
    }

    public SearchResult<Stock> queryPage(int start, int size) {
        Search search = new Search();
        search.setFirstResult(start);
        search.setMaxResults(size);
        return stockDAO.searchAndCount(search);
    }

    public List<Stock> queryListByName(String name) {
        Search search = new Search();
        search.addFilterILike("name", name);
        return stockDAO.search(search);
    }

    public List<Stock> queryListByCode(String code) {
        Search search = new Search();
        search.addFilterILike("code", code);
        return stockDAO.search(search);
    }
}
